package com.sskj.one.transaction;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.constraint.Group;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.hjq.toast.ToastUtils;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.ExitBean;
import com.sskj.lib.bean.TabEntity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.HideUtil;
import com.sskj.one.R;
import com.sskj.one.bean.BuyOrderBean;
import com.sskj.one.bean.GonggaoBean;
import com.sskj.one.bean.HistoryBean;
import com.sskj.one.bean.LastestBean;
import com.sskj.one.bean.MoneyBean;
import com.sskj.one.bean.MoneyListBean;
import com.sskj.one.component.DaggerUserDataComponent;
import com.sskj.one.login.VideoActivity;
import com.sskj.one.mine.DetailGonggaoActivity;
import com.sskj.one.mine.HuiActivity;
import com.sskj.one.util.ArithUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * @author Hey
 * Create at  2019/05/21
 */
public class TransactionFragment extends BaseFragment<TransactionPresenter> {
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tv_mobile;
    @BindView(R.id.iv_music)
    ImageView ivMusic;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.tv_last_money)
    TextView tvLastMoney;
    @BindView(R.id.tv_gouhui)
    TextView tvGouhui;
    @BindView(R.id.tv_jiehui)
    TextView tvJiehui;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.iv_position)
    ImageView iv_position;
    @BindView(R.id.btn_up)
    Button btnUp;
    @BindView(R.id.btn_down)
    Button btnDown;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rl_nodata)
    RelativeLayout rl_nodata;
    @BindView(R.id.rl_count_down)
    RelativeLayout rl_count_down;
    @BindView(R.id.group)
    Group group;
    @BindView(R.id.tv_count_down)
    TextView tv_count_down;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    //玩法介绍
    @BindView(R.id.iv_introduce)
    TextView iv_introduce;
    @Inject
    UserViewModel userViewModel;

    private ChartFragment chartFragment;

    private String buytype;//下注类型

    private UserData userData;

    private String[] mTitles = {"最新盈利", "最新订单"};

    private SlimAdapter<LastestBean> slimAdapter;
    private SlimAdapter<MoneyBean> moneyAdapter;

    private CompositeDisposable compositeDisposable;

    private MoneyListBean moneyListBean;

    private int tabPosition;
    private HashMap<String, Integer> map;
    private DisposableSubscriber<Long> disposableSubscriber;//持仓倒计时
    private Flowable<Long> longFlowable;//持仓倒计时

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_transaction;
    }

    @Override
    public TransactionPresenter getPresenter() {
        return new TransactionPresenter();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (userViewModel != null) {
                userViewModel.update();
            }
        }
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        RxBus.getDefault().register(this);
        compositeDisposable = new CompositeDisposable();
        if (Objects.equals(SPUtil.get(SPConfig.MUSIC_ONE, ""), "1")) {
            ivMusic.setImageResource(R.mipmap.icon_music_open);
        } else {
            ivMusic.setImageResource(R.mipmap.icon_music_close);
        }
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        chartFragment = ChartFragment.newInstance();
        transaction.replace(R.id.kchart_manager, chartFragment);
        transaction.commit();
        map = new HashMap<>();
        map.put("1", R.mipmap.head_one);
        map.put("2", R.mipmap.head_two);
        map.put("3", R.mipmap.head_three);
        map.put("4", R.mipmap.head_four);
        map.put("5", R.mipmap.head_five);
        map.put("6", R.mipmap.head_six);
        map.put("7", R.mipmap.head_seven);
        map.put("8", R.mipmap.head_eight);
        map.put("9", R.mipmap.head_nine);
        map.put("10", R.mipmap.head_ten);
        map.put("11", R.mipmap.head_eleven);
        map.put("12", R.mipmap.head_twelve);
        map.put("13", R.mipmap.head_thirteen);
        map.put("14", R.mipmap.head_fourteen);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                if (isEmpty(userData.getUpic()) || isEmpty(userData.getNickname())) {
                    group.setVisibility(View.GONE);
                    tvNickName.setVisibility(View.VISIBLE);
                } else {
                    group.setVisibility(View.VISIBLE);
                    tvNickName.setVisibility(View.GONE);
                    ImageUtil.setImage(map.get(userData.getUpic()), iv_head);
                }
                tvNickName.setText(HideUtil.getPhoneHide(userData.getMobile()));
                tvName.setText(userData.getNickname());
                tv_mobile.setText(HideUtil.getPhoneHide(userData.getMobile()));
                tvLastMoney.setText("$" + NumberUtil.keep(userData.getUsable(), 5));
                btnLogin.setVisibility(View.GONE);
                llLogin.setVisibility(View.VISIBLE);
            } else {
                userData = null;
                btnLogin.setVisibility(View.VISIBLE);
                llLogin.setVisibility(View.GONE);
            }
        });

        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }
        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                tabPosition = position;
                rl_nodata.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.INVISIBLE);
                getLastestData();
                switch (position) {
                    case 0:
                        tv_type.setText("盈利");
                        break;
                    case 1:
                        tv_type.setText("金额");
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.white));
            return textView;
        });
        initAdapter();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(CoinBean data) {
        if (data.getCode().equals("USDCNY")) {
            if (tv_now_price != null) {
                tv_now_price.setText(NumberUtil.keep(data.getPrice(), 5));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void closeRequest(ExitBean exitBean) {
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }

    private void initAdapter() {
        recyclerView.setLayoutManager(new LinearLayoutManager(App.INSTANCE));
        slimAdapter = SlimAdapter.create().register(R.layout.item_transaction, new SlimInjector<LastestBean>() {
            @Override
            public void onInject(LastestBean data, IViewInjector iViewInjector, List list) {
                iViewInjector
                        .visibility(R.id.ll_user, !isEmpty(data.getUpic()) && !isEmpty(data.getNickname()) ? View.VISIBLE : View.INVISIBLE)
                        .visibility(R.id.tv_mobile, isEmpty(data.getUpic()) || isEmpty(data.getNickname()) ? View.VISIBLE : View.INVISIBLE)
                        .image(R.id.iv_head, isEmpty(data.getUpic()) ? R.mipmap.app_logo : map.get(data.getUpic()))
                        .text(R.id.tv_name, data.getNickname())
                        .text(R.id.tv_mobile, data.getMobile().length() == 11 ? HideUtil.getPhoneHideWrap(data.getMobile()) : data.getMobile())
                        .text(R.id.tv_time,
                                data.getAddtime().contains(" ") ? data.getAddtime().replace(" ", "\n") :
                                        TimeFormatUtil.formatE(Long.valueOf(data.getAddtime()) * 1000).replace(" ", "\n"))
                        .text(R.id.tv_type, data.getOtype().equals("1") ? "买涨" : "买跌")
                        .textColor(R.id.tv_type, data.getOtype().equals("1") ?
                                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme))
                        .text(R.id.tv_money, tabPosition == 0 ? "$" + NumberUtil.keep(data.getProfit(), 5) :
                                tabPosition == 1 ? "$" + NumberUtil.keep(data.getBuynum(), 5) : "$ 0.00000")
                        .text(R.id.tv_exchange_rate, data.getBuyprice());
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
    }

    @Override
    public void initData() {
        mPresenter.getGonggao();
        getLastestData();

        ClickUtil.click(300, ivMusic, () -> {
            if (Objects.equals(SPUtil.get(SPConfig.MUSIC_ONE, ""), "1")) {
                SPUtil.put(SPConfig.MUSIC_ONE, "0");
                ivMusic.setImageResource(R.mipmap.icon_music_close);
            } else {
                SPUtil.put(SPConfig.MUSIC_ONE, "1");
                ivMusic.setImageResource(R.mipmap.icon_music_open);
            }
            RxBus.getDefault().post("open");
        });
        ClickUtil.click(300, tvGouhui, () -> {
            if (userData == null) {
                ToastUtils.show("获取用户信息失败");
                return;
            }
//            if (isEmpty(userData.getBank_nums()) && isEmpty(userData.getAlipay_nums())) {
//                ToastUtils.show("请先添加结汇方式");
//                return;
//            }
            HuiActivity.start(getActivity(), Constans.GOU_HUI);
        });
        ClickUtil.click(300, tvJiehui, () -> {
            if (userData == null) {
                ToastUtils.show("获取用户信息失败");
                return;
            }
            if (isEmpty(userData.getBank_nums()) && isEmpty(userData.getAlipay_nums())) {
                ToastUtils.show("请先添加结汇方式");
                return;
            }
            HuiActivity.start(getActivity(), Constans.JIE_HUI);
        });
        ClickUtil.click(300, btnDown, () -> {
            if (userData == null) {
                return;
            }
            if (moneyListBean == null) {
                mPresenter.getMoneys(Constans.BUY_DOWN);
            } else {
                transaction(getActivity(), moneyListBean, Constans.BUY_DOWN);
            }
        });
        ClickUtil.click(300, btnUp, () -> {
            if (userData == null) {
                return;
            }
            if (moneyListBean == null) {
                mPresenter.getMoneys(Constans.BUY_DOWN);
            } else {
                transaction(getActivity(), moneyListBean, Constans.BUY_UP);
            }
        });
        ClickUtil.click(300, iv_position, () -> {
            RecordPositionActivity.start(getActivity());
        });
        ClickUtil.click(300, rl_count_down, () -> {
            RecordPositionActivity.start(getActivity());
        });
        //玩法介绍
        ClickUtil.click(300, iv_introduce, () -> {
            VideoActivity.start(getActivity(),Constans.VIDEO_WANFA);
        });
    }

    private void getLastestData() {
        compositeDisposable.clear();
        Observable.interval(0, 3, TimeUnit.SECONDS)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new Observer<Long>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (tabPosition == 0) {
                            mPresenter.getNewProfit();
                        } else if (tabPosition == 1) {
                            mPresenter.getNewOrders();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private TextView dialog_tv_up_order;
    private TextView dialog_tv_down_order;
    private TextView dialog_tv_time;
    private TextView dialog_tv_earn;
    private TextView dialog_tv1;
    private TextView dialog_tv_end;
    private TextView dialog_tv_buy_price;
    private TextView dialog_tv_now_price;
    private TextView dialog_tv_price;
    private TextView dialog_tv_type;

    @SuppressLint("SetTextI18n")
    private void transationDialog(HistoryBean historyBean) {
        MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.lib_dialog_transation, false)
                .autoDismiss(true)
                .cancelable(false)
                .show();
        View customView = dialog.getCustomView();
        assert customView != null;
        dialog_tv_up_order = customView.findViewById(R.id.tv_up_order);
        dialog_tv_down_order = customView.findViewById(R.id.tv_down_order);
        dialog_tv_time = customView.findViewById(R.id.tv_time);
        dialog_tv_earn = customView.findViewById(R.id.tv_earn);
        dialog_tv1 = customView.findViewById(R.id.tv1);
        dialog_tv_end = customView.findViewById(R.id.tv_end);
        dialog_tv_buy_price = customView.findViewById(R.id.tv_buy_price);
        dialog_tv_now_price = customView.findViewById(R.id.tv_now_price);
        dialog_tv_price = customView.findViewById(R.id.tv_price);
        dialog_tv_type = customView.findViewById(R.id.tv_type);
        Button dialog_btn_close = customView.findViewById(R.id.btn_close);
        initDialogBean(historyBean);
        ClickUtil.click(dialog_btn_close, dialog::dismiss);
    }

    private void initDialogBean(HistoryBean historyBean) {
        dialog_tv_time.setText(historyBean.getCycle_time() + "s");
        dialog_tv_type.setText("1".equals(historyBean.getOtype()) ? "买涨" : "买跌");
        dialog_tv_earn.setText("$" + NumberUtil.keep(historyBean.getProfit(), 5));
        dialog_tv_buy_price.setText("买入指数：" + historyBean.getBuyprice());
        dialog_tv_now_price.setText("当前指数：" + historyBean.getSellprice());
        dialog_tv_price.setText("保证金：$" + historyBean.getDeposit());
        dialog_tv_end.setText(Float.valueOf(historyBean.getProfit()) > 0 ? "盈" : "亏");
        //弹窗字体颜色  盈：红 亏：绿
        dialog_tv_time.setTextColor(Float.valueOf(historyBean.getProfit()) > 0 ?
                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme));
        dialog_tv_type.setTextColor(Float.valueOf(historyBean.getProfit()) > 0 ?
                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme));
        dialog_tv1.setTextColor(Float.valueOf(historyBean.getProfit()) > 0 ?
                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme));
        dialog_tv_earn.setTextColor(Float.valueOf(historyBean.getProfit()) > 0 ?
                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme));
        dialog_tv_end.setTextColor(Float.valueOf(historyBean.getProfit()) > 0 ?
                ContextCompat.getColor(App.INSTANCE, R.color.color_red) : ContextCompat.getColor(App.INSTANCE, R.color.theme));
        ClickUtil.click(300, dialog_tv_up_order, () -> {
            mPresenter.getLastOrder(historyBean.getTran_id());
        });
        ClickUtil.click(300, dialog_tv_down_order, () -> {
            mPresenter.getNextOrder(historyBean.getTran_id());
        });
    }

    public static TransactionFragment newInstance() {
        TransactionFragment fragment = new TransactionFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    private TextView tv_now_price;
    private String buyMoney;

    public void transaction(Activity activity, MoneyListBean data, String type) {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(activity);
        View inflate = activity.getLayoutInflater().inflate(R.layout.dialog_transaction, null, false);
        RecyclerView money_recyclerView = inflate.findViewById(R.id.money_recyclerView);
        TextView tv_type = inflate.findViewById(R.id.tv_type);
        TextView tv_type_c = inflate.findViewById(R.id.tv_type_c);
        TextView tv_buy = inflate.findViewById(R.id.tv_buy);
        TextView tv_odds = inflate.findViewById(R.id.tv_odds);
        TextView tv_hope_income = inflate.findViewById(R.id.tv_hope_income);
        TextView tv_end_time = inflate.findViewById(R.id.tv_end_time);
        tv_now_price = inflate.findViewById(R.id.tv_now_price);
        Button btn_confirm = inflate.findViewById(R.id.btn_confirm);
        if (type.equals(Constans.BUY_UP)) {
            tv_type.setText("（买涨）");
            tv_type_c.setText("买涨");
            tv_type.setTextColor(ContextCompat.getColor(activity, R.color.color_red));
            tv_type_c.setTextColor(ContextCompat.getColor(activity, R.color.color_red));
        } else if (type.equals(Constans.BUY_DOWN)) {
            tv_type.setText("（买跌）");
            tv_type_c.setText("买跌");
            tv_type.setTextColor(ContextCompat.getColor(activity, R.color.theme));
            tv_type_c.setTextColor(ContextCompat.getColor(activity, R.color.theme));
        }
        List<Integer> isCheck = new ArrayList<>();
        isCheck.add(0);
        if (data.getMargin_amount().size() > 0) {
            tv_buy.setText("$ " + data.getMargin_amount().get(0).getMargin_amount());
            tv_hope_income.setText("$ " + data.getMargin_amount().get(0).getExpected_profit());
            tv_odds.setText(ArithUtil.mul(Double.valueOf(data.getMargin_amount().get(0).getCompensate_rate()), 100) + "%");
            buyMoney = data.getMargin_amount().get(0).getMargin_amount();
        }
        money_recyclerView.setLayoutManager(new GridLayoutManager(activity, 4));
        moneyAdapter = SlimAdapter.create().register(R.layout.item_money, new SlimInjector<MoneyBean>() {
            @Override
            public void onInject(MoneyBean data, IViewInjector iViewInjector, List list) {
                iViewInjector.text(R.id.checkbox, "$ " + data.getMargin_amount())
                        .background(R.id.checkbox, isCheck.contains(moneyAdapter.getData().indexOf(data)) ?
                                ContextCompat.getDrawable(App.INSTANCE, R.drawable.theme_cor5) : ContextCompat.getDrawable(App.INSTANCE, R.drawable.stroke_divide_cor5))
                        .textColor(R.id.checkbox, isCheck.contains(moneyAdapter.getData().indexOf(data)) ?
                                ContextCompat.getColor(App.INSTANCE, R.color.white) : ContextCompat.getColor(App.INSTANCE, R.color.hint))
                        .clicked(R.id.checkbox, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_buy.setText("$ " + data.getMargin_amount());
                                tv_hope_income.setText("$ " + data.getExpected_profit());
                                tv_odds.setText(data.getCompensate_rate());
                                tv_odds.setText(ArithUtil.mul(Double.valueOf(data.getCompensate_rate()), 100) + "%");
                                buyMoney = data.getMargin_amount();
                                if (isCheck.contains(moneyAdapter.getData().indexOf(data))) {
                                    return;
                                } else {
                                    isCheck.clear();
                                    isCheck.add(moneyAdapter.getData().indexOf(data));
                                    moneyAdapter.notifyDataSetChanged();
                                }
                            }
                        });
            }
        }).attachTo(money_recyclerView).updateData(new ArrayList());
        moneyAdapter.updateData(data.getMargin_amount());
        tv_end_time.setText(data.getClose_time() + "s");
        ClickUtil.click(300, btn_confirm, () -> {
            if (isEmpty(buyMoney)) {
                ToastUtils.show("获取信息失败");
                return;
            }
            buytype = type;
            mPresenter.buy(buyMoney, type);
            bottomSheetDialog.dismiss();
        });
        bottomSheetDialog.setContentView(inflate);
        bottomSheetDialog.setCancelable(true);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        bottomSheetDialog.show();
    }

    public void getMoneyOK(MoneyListBean moneys, String buyType) {
        moneyListBean = moneys;
        transaction(getActivity(), moneys, buyType);
    }

    public void getLastestOK(List<LastestBean> data) {
        if (data == null) {
            return;
        }
        recyclerView.setVisibility(View.VISIBLE);
        if (data.size() == 0) {
            rl_nodata.setVisibility(View.VISIBLE);
        } else {
            rl_nodata.setVisibility(View.INVISIBLE);
        }
        if (slimAdapter != null) {
            slimAdapter.updateData(data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
        if (disposableSubscriber != null && !disposableSubscriber.isDisposed()) {
            disposableSubscriber.dispose();
            disposableSubscriber = null;
        }
    }

    public void buyOK(BuyOrderBean buyOrderBean) {
        buyOrderBean.setType(buytype);
        RxBus.getDefault().post(buyOrderBean);
        iv_position.setVisibility(View.GONE);
        rl_count_down.setVisibility(View.VISIBLE);
        userViewModel.update();
        if (buyOrderBean == null || isEmpty(buyOrderBean.getCycle_time())) {
            return;
        }
        if (disposableSubscriber != null && !disposableSubscriber.isDisposed()) {
            disposableSubscriber.dispose();
            disposableSubscriber = null;
        }
        if (longFlowable != null) {
            longFlowable = null;
        }
        longFlowable = Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(Long.valueOf(buyOrderBean.getCycle_time()) + 1)
                .observeOn(AndroidSchedulers.mainThread());
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                tv_count_down.setText("持仓\n" + (Long.valueOf(buyOrderBean.getCycle_time()) - aLong) + "s");
                if ((Long.valueOf(buyOrderBean.getCycle_time()) - aLong) == 0) {
                    mPresenter.getOrder(buyOrderBean.getHold_no());
                }
            }

            @Override
            public void onError(Throwable t) {
            }

            @Override
            public void onComplete() {
//                buyOrderBean.setBuyprice("");
//                RxBus.getDefault().post(buyOrderBean);
                iv_position.setVisibility(View.VISIBLE);
                rl_count_down.setVisibility(View.GONE);
            }
        };
        longFlowable.subscribe(disposableSubscriber);
    }

    private Disposable noticeDispo;
    private GonggaoBean noticeBean;

    public void getGonggaoOK(List<GonggaoBean> data) {
        if (data == null) {
            return;
        }
        if (tvNotice != null) {
            if (data.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeBean = data.get((int) (i % data.size()));
                                tvNotice.setText(noticeBean.getTitle());
                                ClickUtil.click(tvNotice, () -> {
                                    DetailGonggaoActivity.start(getActivity(), noticeBean.getId());
                                });
                            }
                        }, System.out::println);
            }
        }
    }

    public void getOrderOK(HistoryBean data) {
        if (data == null) {
            return;
        }
        initDialogBean(data);
    }

    public void getOrderMsgOK(HistoryBean data) {
        if (data == null) {
            return;
        }
        userViewModel.update();
        transationDialog(data);
    }
}
